<?php

/**
 *    买家的订单管理控制器
 *
 *    @author    Garbin
 *    @usage    none
 */
class Seller_orderApp extends StoreadminbaseApp
{
    function index()
    {
        
        $this->display('seller_order.index.html');
    }

    /**
     *    查看订单详情
     *
     *    @author    Garbin
     *    @return    void
     */
    function view()
    {
        $order_id = isset($_GET['order_id']) ? intval($_GET['order_id']) : 0;
        $config = require ROOT_PATH . '/data/config.qiniu.php';
        $model_order =& m('order');
        $order_info  = $model_order->findAll(array(
            'conditions'    => "order_alias.order_id={$order_id} AND order_alias.is_del=0 AND seller_id=" . $this->visitor->get('manage_store'),
            'join'          => 'has_orderextm',
        ));
        $order_info = current($order_info);
        if (!$order_info)
        {
            $this->show_warning('no_such_order');

            return;
        }

        /* 团购信息 */
        if ($order_info['extension'] == 'groupbuy')
        {
            $groupbuy_mod = &m('groupbuy');
            $group = $groupbuy_mod->get(array(
                'join' => 'be_join',
                'conditions' => 'order_id=' . $order_id,
                'fields' => 'gb.group_id',
            ));
            $this->assign('group_id',$group['group_id']);
        }

        /* 当前位置 */
        $this->_curlocal(LANG::get('member_center'),    'index.php?app=member',
                         LANG::get('order_manage'), 'index.php?app=seller_order',
                         LANG::get('view_order'));

        /* 当前用户中心菜单 */
        $this->_curitem('order_manage');
        $this->_config_seo('title', Lang::get('member_center') . ' - ' . Lang::get('detail'));

        /* 调用相应的订单类型，获取整个订单详情数据 */
        $order_type =& ot($order_info['extension']);
        $order_detail = $order_type->get_order_detail($order_id, $order_info);
        $spec_ids = array();
        $goods_ids = array();
        $goods_model = m('goods');
        foreach ($order_detail['data']['goods_list'] as $key => $goods)
        {
            if($goods['goods_image']){
                $order_detail['data']['goods_list'][$key]['goods_image'] = $goods_model->goodsimg($order_detail['data']['goods_list'][$key]['goods_image']) ;
            }else{
                $order_detail['data']['goods_list'][$key]['goods_image'] = $goods_model->goodsimg(Conf::get('default_goods_image'));
            }
            $spec_ids[] = $goods['spec_id'];
            $goods_ids[] = $goods['goods_id'];
        }

        /* 查出最新的相应的货号 */
        $model_spec =& m('goodsspec');
        $spec_info = $model_spec->find(array(
            'conditions'    => $spec_ids,
            'fields'        => 'sku,spec_1,spec_2',
        ));
        $model_goods = &m('goods');
        $goods_info = $model_goods->find(array('conditions'=>$goods_ids,'fields'=>'spec_name_1,spec_name_2'));

        foreach ($order_detail['data']['goods_list'] as $key => $goods)
        {
            $order_detail['data']['goods_list'][$key]['sku'] = $spec_info[$goods['spec_id']]['sku'];
            $order_detail['data']['goods_list'][$key]['spec_1'] = $spec_info[$goods['spec_id']]['spec_1'];
            $order_detail['data']['goods_list'][$key]['spec_2'] = $spec_info[$goods['spec_id']]['spec_2'];
            $order_detail['data']['goods_list'][$key]['spec_name_1'] = $goods_info[$goods['goods_id']]['spec_name_1'];
            $order_detail['data']['goods_list'][$key]['spec_name_2'] = $goods_info[$goods['goods_id']]['spec_name_2'];
        }

        $this->assign('is_lottery',$model_order->is_lottery($order_id));
        $this->assign('order', $order_info);
        $this->assign($order_detail['data']);
        $this->display('seller_order.view.html');
    }
    /**
     *    收到货款
     *
     *    @author    Garbin
     *    @param    none
     *    @return    void
     */
    function received_pay()
    {
        list($order_id, $order_info)    = $this->_get_valid_order_info(ORDER_PENDING);
        if (!$order_id)
        {
            echo Lang::get('no_such_order');

            return;
        }
        if (!IS_POST)
        {
            header('Content-Type:text/html;charset=' . CHARSET);
            $this->assign('order', $order_info);
            $this->display('seller_order.received_pay.html');
        }
        else
        {
            $model_order    =&  m('order');
            $model_order->edit(intval($order_id), array('status' => ORDER_ACCEPTED, 'pay_time' => gmtime()));
            if ($model_order->has_error())
            {
                $this->pop_warning($model_order->get_error());

                return;
            }

            #TODO 发邮件通知
            /* 记录订单操作日志 */
            $order_log =& m('orderlog');
            $order_log->add(array(
                'order_id'  => $order_id,
                'operator'  => addslashes($this->visitor->get('user_name')),
                'order_status' => order_status($order_info['status']),
                'changed_status' => order_status(ORDER_ACCEPTED),
                'remark'    => $_POST['remark'],
                'log_time'  => gmtime(),
                'order_sn'  => $order_info['order_sn'],
            ));

            /* 发送给买家邮件，提示等待安排发货 */
            $model_member =& m('member');
            $buyer_info   = $model_member->get($order_info['buyer_id']);
            $mail = get_mail('tobuyer_offline_pay_success_notify', array('order' => $order_info));
            $this->_mailto($buyer_info['email'], addslashes($mail['subject']), addslashes($mail['message']));

            $new_data = array(
                'status'    => Lang::get('order_accepted'),
                'actions'   => array(
                    'cancel',
                    'shipped'
                ), //可以取消可以发货
            );

            $this->pop_warning('ok');
        }

    }

    /**
     *    货到付款的订单的确认操作
     *
     *    @author    Garbin
     *    @param    none
     *    @return    void
     */
    function confirm_order()
    {
        list($order_id, $order_info)    = $this->_get_valid_order_info(ORDER_SUBMITTED);
        if (!$order_id)
        {
            echo Lang::get('no_such_order');

            return;
        }
        if (!IS_POST)
        {
            header('Content-Type:text/html;charset=' . CHARSET);
            $this->assign('order', $order_info);
            $this->display('seller_order.confirm.html');
        }
        else
        {
            $model_order    =&  m('order');

            //判断是否为抽奖订单，抽奖订单不可以进行操作订单
            $flag = $model_order->is_lottery($order_id);
            if($flag)
            {
                $this->pop_warning('抽奖类型的订单不可进行此操作');
                return ;
            }

            $model_order->edit($order_id, array('status' => ORDER_ACCEPTED));
            if ($model_order->has_error())
            {
                $this->pop_warning($model_order->get_error());

                return;
            }

            /* 记录订单操作日志 */
            $order_log =& m('orderlog');
            $order_log->add(array(
                'order_id'  => $order_id,
                'operator'  => addslashes($this->visitor->get('user_name')),
                'order_status' => order_status($order_info['status']),
                'changed_status' => order_status(ORDER_ACCEPTED),
                'remark'    => $_POST['remark'],
                'log_time'  => gmtime(),
                'order_sn'  => $order_info['order_sn'],
            ));

            /* 发送给买家邮件，订单已确认，等待安排发货 */
            $model_member =& m('member');
            $buyer_info   = $model_member->get($order_info['buyer_id']);
            $mail = get_mail('tobuyer_confirm_cod_order_notify', array('order' => $order_info));
            $this->_mailto($buyer_info['email'], addslashes($mail['subject']), addslashes($mail['message']));

            $new_data = array(
                'status'    => Lang::get('order_accepted'),
                'actions'   => array(
                    'cancel',
                    'shipped'
                ), //可以取消可以发货
            );

            $this->pop_warning('ok');;
        }
    }

    /**
     *    调整费用
     *
     *    @author    Garbin
     *    @return    void
     */
    function adjust_fee()
    {
        list($order_id, $order_info)    = $this->_get_valid_order_info(array(ORDER_SUBMITTED, ORDER_PENDING));
        if (!$order_id)
        {
            echo Lang::get('no_such_order');

            return;
        }
        $model_order    =&  m('order');
        $model_orderextm =& m('orderextm');
        $shipping_info   = $model_orderextm->get($order_id);
        if (!IS_POST)
        {
            header('Content-Type:text/html;charset=' . CHARSET);
            $this->assign('order', $order_info);
            $this->assign('shipping', $shipping_info);
            $this->display('seller_order.adjust_fee.html');
        }
        else
        {
            /* 配送费用 */
            $shipping_fee = isset($_POST['shipping_fee']) ? abs(floatval($_POST['shipping_fee'])) : 0;
            /* 折扣金额 */
            $goods_amount     = isset($_POST['goods_amount'])     ? abs(floatval($_POST['goods_amount'])) : 0;
            /* 订单实际总金额 */
            $order_amount = round($goods_amount + $shipping_fee, 2);
            if ($order_amount <= 0)
            {
                /* 若商品总价＋配送费用扣队折扣小于等于0，则不是一个有效的数据 */
                $this->pop_warning('invalid_fee');

                return;
            }
            $data = array(
                'goods_amount'  => $goods_amount,    //修改商品总价
                'order_amount'  => $order_amount,     //修改订单实际总金额
                'pay_alter' => 1    //支付变更
            );

            if ($shipping_fee != $shipping_info['shipping_fee'])
            {
                /* 若运费有变，则修改运费 */

                $model_extm =& m('orderextm');
                $model_extm->edit($order_id, array('shipping_fee' => $shipping_fee));
            }
            $model_order->edit($order_id, $data);

            if ($model_order->has_error())
            {
                $this->pop_warning($model_order->get_error());

                return;
            }
            /* 记录订单操作日志 */
            $order_log =& m('orderlog');
            $order_log->add(array(
                'order_id'  => $order_id,
                'operator'  => addslashes($this->visitor->get('user_name')),
                'order_status' => order_status($order_info['status']),
                'changed_status' => order_status($order_info['status']),
                'remark'    => Lang::get('adjust_fee'),
                'log_time'  => gmtime(),
                'order_sn'  => $order_info['order_sn'],
            ));

            /* 发送给买家邮件通知，订单金额已改变，等待付款 */
            $model_member =& m('member');
            $buyer_info   = $model_member->get($order_info['buyer_id']);
            $mail = get_mail('tobuyer_adjust_fee_notify', array('order' => $order_info));
            $this->_mailto($buyer_info['email'], addslashes($mail['subject']), addslashes($mail['message']));

            $new_data = array(
                'order_amount'  => price_format($order_amount),
            );

            $this->pop_warning('ok');
        }
    }

    /**
     *    待发货的订单发货
     *
     *    @author    Garbin
     *    @return    void
     */
    function shipped()
    {
        list($order_id, $order_info)    = $this->_get_valid_order_info(array(ORDER_ACCEPTED, ORDER_SHIPPED));
        if (!$order_id)
        {
            echo Lang::get('no_such_order');

            return;
        }
        $model_order    =&  m('order');

        $express_list = $this->expresslist();

        if (!IS_POST)
        {
            /* 显示发货表单 */
            header('Content-Type:text/html;charset=' . CHARSET);
            $this->assign('order', $order_info);
            $this->assign('express_list', $express_list);
            $this->display('seller_order.shipped.html');
        }
        else
        {
            //抽奖订单不可进行此项操作
            $flag = $model_order->is_lottery($order_id);
            if($flag)
            {
                $this->pop_warning('抽奖订单不可进行此项操作');
                return ;
            }

            if (!$_POST['invoice_no'])
            {
                $this->pop_warning('invoice_no_empty');

                return;
            }
            $express = trim($_POST['express']);
            if(!in_array($express,$express_list)){
                $this->pop_warning('请选择快递公司');

                return;
            }

            $edit_data = array('status' => ORDER_SHIPPED, 'invoice_no' => $_POST['invoice_no'],'expressname'=>$express);
            $is_edit = true;
            if (empty($order_info['invoice_no']))
            {
                /* 不是修改发货单号 */
                $edit_data['ship_time'] = gmtime();
                $is_edit = false;
            }
            $model_order->edit(intval($order_id), $edit_data);
            if ($model_order->has_error())
            {
                $this->pop_warning($model_order->get_error());

                return;
            }

            #TODO 发邮件通知
            /* 记录订单操作日志 */
            $order_log =& m('orderlog');
            $order_log->add(array(
                'order_id'  => $order_id,
                'operator'  => addslashes($this->visitor->get('user_name')),
                'order_status' => order_status($order_info['status']),
                'changed_status' => order_status(ORDER_SHIPPED),
                'remark'    => $_POST['remark'],
                'log_time'  => gmtime(),
                'order_sn'  => $order_info['order_sn'],
            ));


            /* 发送给买家订单已发货通知 */
            $model_member =& m('member');
            $buyer_info   = $model_member->get($order_info['buyer_id']);
            $order_info['invoice_no'] = $edit_data['invoice_no'];
            $mail = get_mail('tobuyer_shipped_notify', array('order' => $order_info));
            $this->_mailto($buyer_info['email'], addslashes($mail['subject']), addslashes($mail['message']));

            $new_data = array(
                'status'    => Lang::get('order_shipped'),
                'actions'   => array(
                    'cancel',
                    'edit_invoice_no'
                ), //可以取消可以发货
            );
            if ($order_info['payment_code'] == 'cod')
            {
                $new_data['actions'][] = 'finish';
            }

            //给收货人发短信
            $mod = m('sms');
            $sql = "select * from ".$mod->_prefix."order_extm where order_id='{$order_id}'";
            $ext = $mod->getRow($sql);
            if(!empty($ext) && $this->is_phone($ext['phone_mob']))
            {
                $mod->sendMessage($ext['phone_mob'],'尊贵的陛下，您在He She贺喜钦点的时尚恩宠已快马加鞭奔赴朝中，请您耐心等待。记得常翻He She贺喜牌子哟。【贺喜时尚】');
            }


            //还要更新对应的记录
            if(!empty($ext))
            {
                $k_id = 0;
                foreach($express_list as  $k=>$val)
                {
                    if($val == $express)
                    {
                        $k_id=$k;
                        break;
                    }
                }

                if($k_id != 0)
                {
                    $temp = array('shipping_id'=>$k_id,'shipping_name'=>$express);

                    $sql = "update ".$mod->_prefix."order_extm set shipping_id='{$k_id}' ,shipping_name='{$express}' where order_id='{$ext['order_id']}' limit 1 ";
                    $mod->query($sql);
                }

            }

            $this->pop_warning('ok');
        }
    }

    /**
     *    取消订单
     *
     *    @author    Garbin
     *    @return    void
     */
    function cancel_order()
    {
        /* 取消的和完成的订单不能再取消 */
        //list($order_id, $order_info)    = $this->_get_valid_order_info(array(ORDER_SUBMITTED, ORDER_PENDING, ORDER_ACCEPTED, ORDER_SHIPPED));
        $order_id = isset($_GET['order_id']) ? trim($_GET['order_id']) : '';
        if (!$order_id)
        {
            echo Lang::get('no_such_order');
        }
        $status = array(ORDER_SUBMITTED, ORDER_PENDING, ORDER_ACCEPTED, ORDER_SHIPPED);
        $order_ids = explode(',', $order_id);
        if ($ext)
        {
            $ext = ' AND ' . $ext;
        }

        $model_order    =&  m('order');
        /* 只有已发货的货到付款订单可以收货 */
        $order_info     = $model_order->find(array(
            'conditions'    => "order_id" . db_create_in($order_ids) . " AND is_del=0 AND seller_id=" . $this->visitor->get('manage_store') . " AND status " . db_create_in($status) . $ext,
        ));
        $ids = array_keys($order_info);
        if (!$order_info)
        {
            echo Lang::get('no_such_order');

            return;
        }
        if (!IS_POST)
        {
            header('Content-Type:text/html;charset=' . CHARSET);
            $this->assign('orders', $order_info);
            $this->assign('order_id', count($ids) == 1 ? current($ids) : implode(',', $ids));
            $this->display('seller_order.cancel.html');
        }
        else
        {
            $model_order    =&  m('order');
            foreach ($ids as $val)
            {
                $id = intval($val);
                $model_order->edit($id, array('status' => ORDER_CANCELED));
                if ($model_order->has_error())
                {
                    //$_erros = $model_order->get_error();
                    //$error = current($_errors);
                    //$this->json_error(Lang::get($error['msg']));
                    //return;
                    continue;
                }

                /* 加回订单商品库存 */
                $model_order->change_stock('+', $id);
                $cancel_reason = (!empty($_POST['remark'])) ? $_POST['remark'] : $_POST['cancel_reason'];
                /* 记录订单操作日志 */
                $order_log =& m('orderlog');
                $order_log->add(array(
                    'order_id'  => $id,
                    'operator'  => addslashes($this->visitor->get('user_name')),
                    'order_status' => order_status($order_info[$id]['status']),
                    'changed_status' => order_status(ORDER_CANCELED),
                    'remark'    => $cancel_reason,
                    'log_time'  => gmtime(),
                    'order_sn'  => $order_info[$id]['order_sn'],
                ));

                /* 发送给买家订单取消通知 */
                $model_member =& m('member');
                $buyer_info   = $model_member->get($order_info[$id]['buyer_id']);
                $mail = get_mail('tobuyer_cancel_order_notify', array('order' => $order_info[$id], 'reason' => $_POST['remark']));
                $this->_mailto($buyer_info['email'], addslashes($mail['subject']), addslashes($mail['message']));

                $new_data = array(
                    'status'    => Lang::get('order_canceled'),
                    'actions'   => array(), //取消订单后就不能做任何操作了
                );
            }
            $this->pop_warning('ok', 'seller_order_cancel_order');
        }

    }

    /**
     *    完成交易(货到付款的订单)
     *
     *    @author    Garbin
     *    @return    void
     */
    function finished()
    {
        list($order_id, $order_info)    = $this->_get_valid_order_info(ORDER_SHIPPED, 'payment_code=\'cod\'');
        if (!$order_id)
        {
            echo Lang::get('no_such_order');

            return;
        }
        if (!IS_POST)
        {
            header('Content-Type:text/html;charset=' . CHARSET);
            /* 当前用户中心菜单 */
            $this->_curitem('seller_order');
            /* 当前所处子菜单 */
            $this->_curmenu('finished');
            $this->assign('_curmenu','finished');
            $this->assign('order', $order_info);
            $this->display('seller_order.finished.html');
        }
        else
        {
            $now = gmtime();
            $model_order    =&  m('order');
            //检查是否为抽奖订单
            $flag = $model_order->is_lottery($order_id);
            if($flag)
            {
                $this->pop_warning('抽奖订单不可进行此项操作');
                return false;
            }

            $model_order->edit($order_id, array('status' => ORDER_FINISHED, 'pay_time' => $now, 'finished_time' => $now));
            if ($model_order->has_error())
            {
                $this->pop_warning($model_order->get_error());
                return;
            }

            /* 记录订单操作日志 */
            $order_log =& m('orderlog');
            $order_log->add(array(
                'order_id'  => $order_id,
                'operator'  => addslashes($this->visitor->get('user_name')),
                'order_status' => order_status($order_info['status']),
                'changed_status' => order_status(ORDER_FINISHED),
                'remark'    => $_POST['remark'],
                'log_time'  => gmtime(),
                'order_sn'  =>$order_info['order_sn'],
            ));

            /* 更新累计销售件数 */
            $model_goodsstatistics =& m('goodsstatistics');
            $model_ordergoods =& m('ordergoods');
            $order_goods = $model_ordergoods->find("order_id={$order_id}");
            foreach ($order_goods as $goods)
            {
                $model_goodsstatistics->edit($goods['goods_id'], "sales=sales+{$goods['quantity']}");
            }
            
            
            /* 发送给买家交易完成通知，提示评论 */
            $model_member =& m('member');
            $buyer_info   = $model_member->get($order_info['buyer_id']);
            $mail = get_mail('tobuyer_cod_order_finish_notify', array('order' => $order_info));
            $this->_mailto($buyer_info['email'], addslashes($mail['subject']), addslashes($mail['message']));

            $new_data = array(
                'status'    => Lang::get('order_finished'),
                'actions'   => array(), //完成订单后就不能做任何操作了
            );

            $this->pop_warning('ok');
        }

    }

    /**
     *    获取有效的订单信息
     *
     *    @author    Garbin
     *    @param     array $status
     *    @param     string $ext
     *    @return    array
     */
    function _get_valid_order_info($status, $ext = '')
    {
        $order_id = isset($_GET['order_id']) ? intval($_GET['order_id']) : 0;
        if (!$order_id)
        {

            return array();
        }
        if (!is_array($status))
        {
            $status = array($status);
        }

        if ($ext)
        {
            $ext = ' AND ' . $ext;
        }

        $model_order    =&  m('order');
        /* 只有已发货的货到付款订单可以收货 */
        $order_info     = $model_order->get(array(
            'conditions'    => "order_id={$order_id} AND is_del=0 AND seller_id=" . $this->visitor->get('manage_store') . " AND status " . db_create_in($status) . $ext,
        ));
        if (empty($order_info))
        {

            return array();
        }

        return array($order_id, $order_info);
    }
    /**
     *    获取订单列表
     *
     *    @author    Garbin
     *    @return    void
     */
    function _get_orders()
    {
        $config = require ROOT_PATH.'/data/config.qiniu.php';
        $page = $this->_get_page();
        $model_order =& m('order');

        !$_GET['type'] && $_GET['type'] = 'all_orders';

        $conditions = ' and order_alias.is_del=0 ';

        // 团购订单
        if (!empty($_GET['group_id']) && intval($_GET['group_id']) > 0)
        {
            $groupbuy_mod = m('groupbuy');
            $order_ids = $groupbuy_mod->get_order_ids(intval($_GET['group_id']));
            $order_ids && $conditions .= ' AND order_alias.order_id' . db_create_in($order_ids);
        }

        $conditions .= $this->_get_query_conditions(array(
            array(      //按订单状态搜索
                'field' => 'status',
                'name'  => 'type',
                'handler' => 'order_status_translator',
            ),
            array(      //按买家名称搜索
                'field' => 'buyer_name',
                'equal' => 'LIKE',
            ),
            array(      //按下单时间搜索,起始时间
                'field' => 'add_time',
                'name'  => 'add_time_from',
                'equal' => '>=',
                'handler'=> 'gmstr2time',
            ),
            array(      //按下单时间搜索,结束时间
                'field' => 'add_time',
                'name'  => 'add_time_to',
                'equal' => '<=',
                'handler'=> 'gmstr2time_end',
            ),
            array(      //按订单号
                'field' => 'order_sn',
            ),
        ));

        /* 查找订单 */
        $orders = $model_order->findAll(array(
            'conditions'    => "seller_id=" . $this->visitor->get('manage_store') . "{$conditions}",
            'count'         => true,
            'join'          => 'has_orderextm',
            'limit'         => $page['limit'],
            'order'         => 'add_time DESC',
            'include'       =>  array(
                'has_ordergoods',       //取出商品
            ),
        ));



        foreach ($orders as $key1 => $order)
        {
            $order['add_time'] = $order['add_time'] ? date('Y-m-d H:i:s', $order['add_time']) : '';
            $order['pay_time'] = $order['pay_time'] ? date('Y-m-d H:i:s', $order['pay_time']) : '';
            foreach ((array)$order['order_goods'] as $key2 => $goods)
            {
                $goods['goods_image'] = $goods['goods_image'] ? $config['qiniu_url'].$goods['goods_image'] : Conf::get('default_goods_image');
                $order['order_goods'][$key2] = $goods;
            }



            if(count($order['order_goods']) ==1)
            {
                $order['lottery'] = $model_order->is_lottery($order['order_id']);


                //var_dump($order['lottery']);
            }

            $orders[$key1] = $order;
        }

        $page['item_count'] = $model_order->getCount();
        $this->_format_page($page);
        $this->assign('types', array('all' => Lang::get('all_orders'),
                                     'pending' => Lang::get('pending_orders'),
                                     'submitted' => Lang::get('submitted_orders'),
                                     'accepted' => Lang::get('accepted_orders'),
                                     'shipped' => Lang::get('shipped_orders'),
                                     'finished' => Lang::get('finished_orders'),
                                     'canceled' => Lang::get('canceled_orders')));


        $this->assign('type', $_GET['type']);
        $this->assign('orders', $orders);
        $this->assign('page_info', $page);
    }
    /*三级菜单*/
    function _get_member_submenu()
    {
        $array = array(
            array(
                'name' => 'all_orders',
                'url' => 'index.php?app=seller_order&amp;type=all_orders',
            ),
            array(
                'name' => 'pending',
                'url' => 'index.php?app=seller_order&amp;type=pending',
            ),
            array(
                'name' => 'submitted',
                'url' => 'index.php?app=seller_order&amp;type=submitted',
            ),
            array(
                'name' => 'accepted',
                'url' => 'index.php?app=seller_order&amp;type=accepted',
            ),
            array(
                'name' => 'shipped',
                'url' => 'index.php?app=seller_order&amp;type=shipped',
            ),
            array(
                'name' => 'finished',
                'url' => 'index.php?app=seller_order&amp;type=finished',
            ),
            array(
                'name' => 'canceled',
                'url' => 'index.php?app=seller_order&amp;type=canceled',
        ),
        );
        return $array;
    }

    /**
     * 批量查看订单详情
     */
    public function batchview()
    {
        $config = require ROOT_PATH . '/data/config.qiniu.php';

        $time = microtime(true);
        $order_ids = $this->get_gp('oids');
        $order_ids = explode(',',$order_ids);
        $order_ids = array_filter($order_ids);
        $order_ids = array_filter($order_ids,function($val){return is_numeric($val);});

        if(empty($order_ids) || !is_array($order_ids)){
            $this->show_warning("参数有误");return;
        }



        $config = require ROOT_PATH . '/data/config.qiniu.php';
        $model_order =& m('order');
        $order_infos  = $model_order->findAll(array(
            'conditions'    => "order_alias.order_id  in (". implode(',',$order_ids) .") AND order_alias.is_del=0 AND seller_id=" . $this->visitor->get('manage_store')." and extension='normal' ",
            'join'          => 'has_orderextm',
        ));
        $order_info = current($order_infos);
        if (empty($order_info) || !is_array($order_info))
        {
            $this->show_warning('no_such_order');
            return;
        }



        /* 当前位置 */
        $this->_curlocal(LANG::get('member_center'),    'index.php?app=member',
            LANG::get('order_manage'), 'index.php?app=seller_order',
            LANG::get('view_order'));

        /* 当前用户中心菜单 */
        $this->_curitem('order_manage');
        $this->_config_seo('title', Lang::get('member_center') . ' - ' . Lang::get('detail'));


        /* 获取商品列表 */
        $order_ids = array_keys($order_infos);
        $ordergoods_model =& m('ordergoods');
        $goods_list = $ordergoods_model->find("order_id in (". implode(',',$order_ids) .")");

        $goods_order_list = array();
        $spec_ids = array();
        $goods_ids = array();
        foreach($goods_list as $val)
        {
            //
            $val['goods_image'] = empty($val['goods_image'])?Conf::get('default_goods_image'):$config['qiniu_url'].$val['goods_image'];

            $goods_order_list[$val['order_id']][] = $val;
            $spec_ids[$val['spec_id']] = $val['spec_id'];
            $goods_ids[$val['goods_id']] = $val['goods_id'];
        }

        /* 配关信息 */
        $orderextm_model =& m('orderextm');

        $orderextm = $orderextm_model->find("order_id in (". implode(',',$order_ids) .")");
        $order_ext = array();
        foreach($orderextm as $val)
        {
            $order_ext[$val['order_id']] = $val;
        }

        /* 支付方式信息 */
        $payment_model      =& m('payment');
        $payment_info       =  $payment_model->find("1");
        //echo '<pre>';print_r($payment_info);exit;

        /* 订单操作日志 */
        $model_orderlog =& m('orderlog');

        $orderlogdata = $model_orderlog->find("order_id in (". implode(',',$order_ids) .")");
        $order_logs_data = array();
        foreach($orderlogdata as $val)
        {
            $order_logs_data[$val['order_id']][] = $val;
        }

        //找到订单的详情内容


        /* 查出最新的相应的货号 */
        $model_spec =& m('goodsspec');
        $spec_info = $model_spec->find(array(
            'conditions'    => $spec_ids,
            'fields'        => 'sku,spec_1,spec_2',
        ));

        //商品信息
        $model_goods = m('goods');
        $goods_info = $model_goods->find(array(
            'conditions'    => $goods_ids,
            'fields'        => 'goods_id,spec_name_1,spec_name_1',
        ));



        ///下面进行数据组装
        foreach($order_infos as $key=>$order)
        {
            if(!isset($goods_order_list[$order['order_id']])){
                unset($order_info[$key]);
                continue;
            }

            //商品规格和列表
            $order['goodslist'] = $goods_order_list[$order['order_id']];
            foreach($order['goodslist'] as $k=>$goods)
            {
                if(!isset($spec_info[$goods['spec_id']]))
                {
                    continue;
                }

                $goods['spec_name_1'] = empty($goods_info[$goods['goods_id']]['spec_name_1'])?'颜色':$goods_info[$goods['goods_id']]['spec_name_1'];
                $goods['spec_name_2'] = empty($goods_info[$goods['goods_id']]['spec_name_2'])?'尺码':$goods_info[$goods['goods_id']]['spec_name_2'];


                $goods['specinfo'] = isset($spec_info[$goods['spec_id']])?$spec_info[$goods['spec_id']]:array();
                $order['goodslist'][$k] = $goods;
            }


            //logs
            $order['logs'] = isset($order_logs_data[$order['order_id']])?$order_logs_data[$order['order_id']]:array();

            //配送信息
            $order['order_ext'] = isset($order_ext[$order['order_id']])?$order_ext[$order['order_id']]:array();

            //payment
            $order['payment_info'] = isset($payment_info[$order['payment_id']])?$payment_info[$order['payment_id']]:array();

            //看是否是抽奖订单
            $order['lottery'] = $model_order->is_lottery($order['order_id']);

            $order_infos[$key] = $order;
        }


        //echo '<pre>';print_r($order_infos);exit;
        //$end = microtime(true);

        //echo $time,"|||",$end;exit;


        $this->assign('order_infos',$order_infos);
        //exit;
        $this->display('seller_order.batchview.html');
    }


    /**
     * 下载导出的处理
     */
    function download()
    {
        $_REQUEST['page'] = 1;
        $page = $this->_get_page(1000);
        $model_order =& m('order');

        !$_GET['type'] && $_GET['type'] = 'all_orders';

        $conditions = ' AND is_del=0 ';

        $conditions .= $this->_get_query_conditions(array(
            array(      //按订单状态搜索
                'field' => 'status',
                'name'  => 'type',
                'handler' => 'order_status_translator',
            ),
            array(      //按买家名称搜索
                'field' => 'buyer_name',
                'equal' => 'LIKE',
            ),

            array(      //按订单号
                'field' => 'order_sn',
            ),
        ));

        $add_time_from = $this->get_gp('add_time_from');
        $add_time_to = $this->get_gp('add_time_to');

        if($add_time_from){
            $inx = strtotime($add_time_from);
            if($inx){
                $conditions .= " AND add_time >='{$inx}' ";
            }
        }

        if($add_time_to){
            $inx = strtotime($add_time_to);
            if($inx){
                $inx += 86400;
                $conditions .= " AND add_time <='{$inx}' ";
            }
        }
        /* 查找订单 */
        $orders = (array)$model_order->findAll(array(
            'conditions'    => "seller_id=" . $this->visitor->get('manage_store') . "{$conditions}",
            'count'         => true,
            'join'          => 'has_orderextm',
            'limit'         => $page['limit'],
            'order'         => 'add_time DESC',
//            'include'       =>  array(
//                'has_ordergoods',       //取出商品
//            ),
        ));

        $title = array('订单编号','买家','收货人姓名','买家备注','下单时间','支付时间','电话号码','支付方式','订单总价','订单状态');

        $data = array();
        foreach ($orders as $key1 => $order)
        {
            $temp = array();
            $temp[] = $order['order_sn'];
            $temp[] = $order['buyer_name'];
            $temp[] = $order['consignee'];
            $temp[] = $order['postscript'];

            $temp[] = $order['add_time'] ? date('Y-m-d H:i:s', $order['add_time']) : '';
            $temp[] = $order['pay_time'] ? date('Y-m-d H:i:s', $order['pay_time']) : '';
            $temp[] = $order['phone_mob']?$order['phone_mob']:$order['phone_tel'];
            $temp[] = $order['payment_name'];
            $temp[] = $order['order_amount'];
            $temp[] = order_status($order['status']);
            $data[] = $temp;
        }
        unset($orders);
        //准备下载
        require_once ROOT_PATH.'/includes/libraries/csv.lib.php';

        $m = new CSVLIB();


        $m->export_csv($data,$title,'订单导出'.date('Y_m_d'));

    }

    /**
     * 对抽奖中的一些设置
     * auth bzyy
     * 2015年10月9日11:30:57
     *
     */
    public function lottery()
    {

        //先判断此订单是否符合，
        //此订单是否可以操作
        //处理操作
        //记录日志

        $order_id = $this->get_gp('order_id');
        $model_order    =&  m('order');
        $order_info = $model_order->get_info($order_id);


        if (!IS_POST)
        {
            $this->assign('order_id',$order_id);
            $this->display('seller_order.lottery.html');
        }
        else
        {
            $flag = $model_order->check_lottery_done($order_info);
            if(!$flag )
            {
                $this->pop_warning($model_order->get_error());exit;
            }

            $done = $this->get_gp('done');
            $reason = trim($this->get_gp('reason'));

            if(empty($reason))
            {
                //$this->pop_warning('备注不可为空');return ;
                $reason = '[系统]没有备注';
            }

            if($done != 1)
            {
                $this->pop_warning('数据有误');exit;
            }

            //进行操作

            $edit_data = array('status' => ORDER_FINISHED);

            $model_order->edit(intval($order_id), $edit_data);
            if ($model_order->has_error())
            {
                $this->pop_warning($model_order->get_error());
                return;
            }

            /* 记录订单操作日志 */
            $order_log =& m('orderlog');
            $order_log->add(array(
                'order_id'  => $order_id,
                'operator'  => addslashes($this->visitor->get('user_name')),
                'order_status' => order_status($order_info['status']),
                'changed_status' => order_status(ORDER_FINISHED),
                'remark'    => $reason,
                'log_time'  => gmtime(),
                'order_sn'  => $order_info['order_sn'],
            ));

            $this->pop_warning('ok', 'seller_order_lottery');
        }
    }


    //快递公司的处理
    protected function expresslist()
    {

        $m = m('shipexpress');

        $data = $m->findAll();

        $data1 = array();

        foreach($data as $val)
        {
            $data1[$val['id']] = $val['name'];
        }

        return $data1;
    }





}

?>
